package com.xh.core.handler;

import com.aspose.words.DocumentBuilder;
import com.aspose.words.FieldMergingArgs;
import com.aspose.words.IFieldMergingCallback;
import com.aspose.words.ImageFieldMergingArgs;
import com.xh.core.constant.FormularDisplayTypeConstant;
import com.xh.core.exception.XhException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/*
 * @Author daiwei
 * @Description
 * @Date 2019/5/10 18:11
 **/
public class MergeFieldTextbookHtmlHandle implements IFieldMergingCallback {

    //公式展示类型
    private Integer formularDisplayType= FormularDisplayTypeConstant.IMAGE;
    private String[] htmlFields;


    public MergeFieldTextbookHtmlHandle(){
        this.formularDisplayType= FormularDisplayTypeConstant.IMAGE;
        this.htmlFields=null;
    }

    /**
     * 构造方法
     * @param formularDisplayType 公式显示类型
     * @param htmlFields 需要进行html处理的域名
     */
    public MergeFieldTextbookHtmlHandle(Integer formularDisplayType,String... htmlFields){
        this.formularDisplayType= formularDisplayType;
        this.htmlFields=htmlFields;
    }

    @Override
    public void fieldMerging(FieldMergingArgs e) throws Exception {
        if(htmlFields==null||htmlFields.length==0){
            return;
        }
        boolean flag=false;

        for(String fieldName : htmlFields){
            if(e.getDocumentFieldName().equals(fieldName)){
                flag=true;
                break;
            }
        }

        if (flag)
        {
            String html = e.getFieldValue() == null?"":e.getFieldValue().toString();
            if(formularDisplayType.equals(FormularDisplayTypeConstant.IMAGE)){

            }else if(formularDisplayType.equals(FormularDisplayTypeConstant.MATHTYPE_EDITABLE)){
                throw new XhException("暂不支持MathType格式公式导出");
            }else if(formularDisplayType.equals(FormularDisplayTypeConstant.MS_OFFICE_EDITABLE)){
                throw new XhException("暂不支持微软格式公式导出");
            }else if(formularDisplayType==FormularDisplayTypeConstant.LATEX_SOURCE) {
                Document doc = Jsoup.parse(html);
                Elements latexImgs = doc.getElementsByAttribute("data-latex");
                for (Element latexImg : latexImgs) {
                    latexImg.after("$" + latexImg.attr("data-latex") + "$");
                    latexImg.remove();
                }
                html = doc.body().html();
            }

             // 使用DocumentBuilder处理图片的大小
            DocumentBuilder builder = new DocumentBuilder(e.getDocument());

            builder.moveToMergeField(e.getFieldName());
            builder.insertHtml(html);
        }

    }

    @Override
    public void imageFieldMerging(ImageFieldMergingArgs imageFieldMergingArgs) throws Exception {

    }
}
